package com.gowants.pems.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gowants.pems.aspect.Importance;
import com.gowants.pems.aspect.OperType;
import com.gowants.pems.aspect.ScmsAopLog;
import com.gowants.pems.config.AccessLimit;
import com.gowants.pems.mapper.EquipmentFaultMapper;
import com.gowants.pems.mapper.EquipmentKnowledgeMapper;
import com.gowants.pems.model.EquipmentFault;
import com.gowants.pems.model.EquipmentFaultFile;
import com.gowants.pems.model.EquipmentKnowledge;
import com.gowants.pems.model.EquipmentKnowledgeFile;
import com.gowants.pems.service.EquipmentFaultService;
import com.gowants.pems.service.EquipmentKnowledgeService;
import com.gowants.pems.service.ParamsService;
import com.gowants.pems.util.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/equipmentKnowledge/")
public class EquipmentKnowledgeController extends BaseController {

    @Autowired
    private EquipmentKnowledgeMapper mapper;

    @Autowired
    private EquipmentKnowledgeService service;

    @Autowired
    private ParamsService paramsService;


    /**
     * 获取设备列表
     * @param page
     * @param limit
     * @param reqData
     * @param req
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "设备知识库列表查看", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap getList(@RequestParam(defaultValue = "1", required = false, value = "page") int page,
                           @RequestParam(defaultValue = "10", required = false, value = "limit") int limit,
                           @RequestParam(defaultValue = "", required = false, value = "reqData") String reqData,
                           HttpServletRequest req)
    {
        if (!isPower("/equipmentKnowledge/getList.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        JSONMap resultMap = new JSONMap();
        EquipmentKnowledge record = new EquipmentKnowledge();
        if (!"".equals(reqData))
        {
            JSONList jsonCondition = getCondition(reqData);

            for (Object cond : jsonCondition) {
                this.buildCondition(cond, record);
            }
        }
        if(StringUtils.isNotBlank(getUser().getOwnerId())) {
        	record.setOwner(getUser().getOwnerId());
        }
        // 设置分页查询信息
        PageHelper.startPage(page, limit);
        List<EquipmentKnowledge> list = mapper.select(record);
        PageInfo<EquipmentKnowledge> pageInfo = new PageInfo<EquipmentKnowledge>(list);
        // 赋值方法
        pageSetData(req, resultMap, page,  limit, pageInfo.getPages(),"", list, pageInfo.getTotal());

        return doResponse(req, "", resultMap);
    }

    @RequestMapping(value = "/getOneEquipmentKnowledge", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "设备知识库检索", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap getOneEquipmentKnowledge(String request, HttpServletRequest req){
        EquipmentKnowledge equipment=new EquipmentKnowledge();
        String code ="";
        if (!isPower("/equipmentKnowledge/getOneEquipmentKnowledge.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String id = requestBody.getString("id");
            equipment = mapper.selectById(id);
            String path = paramsService.getParamValueByNumber(Const.equipment_fault_file_mapping);
            List<EquipmentKnowledgeFile> list = equipment.getListFile().stream().map(m->{
                m.setAddressZh(path+m.getAddress());
                return m;
            }).collect(Collectors.toList());
            equipment.setListFile(list);
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, equipment);
    }



    @RequestMapping(value = "/saveEquipmentKnowledge", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "设备知识库保存", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap saveEquipmentKnowledge(String request, HttpServletRequest req){
        if (!isPower("/equipmentKnowledge/saveEquipmentKnowledge.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000036";
        try
        {
            EquipmentKnowledge record = getRequestBody(request, EquipmentKnowledge.class);
            record.setId(UUID.randomUUID().toString());
            record.setCreateUid(getUserId());
            record.setCreateTime(DateUtil.getDate());
            int exeNum = service.saveEquipmentKnowledge(record);
            code = "TSMS_0000001";
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    }

    @RequestMapping(value = "/editEquipmentKnowledge", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "设备知识库修改", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap editEquipmentKnowledge(String request, HttpServletRequest req){
        if (!isPower("/equipmentKnowledge/editEquipmentKnowledge.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000053";
        try
        {
            EquipmentKnowledge record = getRequestBody(request, EquipmentKnowledge.class);

            int exeNum = service.editEquipmentKnowledge(record);
            if(exeNum > 0)
            {
                code = "TSMS_0000001";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    }


    /**
     * <删除>
     * @param request
     * @param req
     * @return
     * @remake
     */
    @RequestMapping(value = "/deleteEquipmentKnowledge", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "设备知识库删除", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap deleteEquipmentKnowledge(String request, HttpServletRequest req)
    {
        if (!isPower("/equipmentKnowledge/deleteEquipmentKnowledge.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000048";
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String id = requestBody.getString("id");
            int exeNum = service.deleteEquipmentKnowledge(id);
            if(exeNum > 0)
            {
                code = "TSMS_0000050";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }
        return doResponse(req, code, null);
    }

    /**
     * <删除>
     * @param request
     * @param req
     * @return
     * @remake
     */
    @RequestMapping(value = "/deleteEquipmentKnowledgeFile", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "设备知识库附件删除", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap deleteEquipmentKnowledgeFile(String request, HttpServletRequest req)
    {
        if (!isPower("/equipmentKnowledge/deleteEquipmentKnowledgeFile.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000048";
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String address = requestBody.getString("address");
            int exeNum = mapper.deleteFileByAddress(address);
            int i= mapper.selectByAddress(address);
            if(exeNum > 0||i==0)
            {
                code = "TSMS_0000050";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }
        return doResponse(req, code, null);
    }


    @RequestMapping(value = "uploadEquipmentKnowledge")
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    public JSONMap uploadEquipmentKnowledge(MultipartFile myFile, HttpServletRequest req) {
        String code = "";
        try {

            // 校验上传文件
            int checkResult = service.uploadCheck(myFile, Const.equipment_fault_file_type, Const.equipment_fault_file_size);

            // 文件超出限制大小
            if (checkResult == -1) {
                return doResponse(req, "TSMS_0000025");
            }

            // 文件格式不对
            if (checkResult == 0) {
                return doResponse(req, "TSMS_0000026");
            }
            String path = service.upload(myFile, Const.equipment_fault_file_path, null, Const.equipment_fault_file_mapping, true, true);
            if ("".equals(path)) {
                return doResponse(req, "TSMS_0000089");
            }
            JSONMap resultMap = new JSONMap();
            resultMap.put("path", path);
            return doResponse(req, code, resultMap);

        } catch (Exception e) {
            code = e.getMessage();
            return doResponse(req, code, null);
        }
    }

    /**
     * <下载>
     *
     * @param filePath
     * @param response
     * @remake 2020.12.01
     */
    @RequestMapping(value = "/download")
    @AccessLimit(seconds = 1, maxCount = 3, needLogin = true) // 1秒内 允许请求3次
    public void download(String filePath, HttpServletResponse response) {

        try {
            String path = paramsService.getParamValueByNumber(Const.equipment_file_path);
            DownLoadUtil.downLoad(path + filePath, response, false);
        } catch (Exception e) {
            return;
        }

    }


    private void buildCondition(Object cond, EquipmentKnowledge record)
    {
        JSONMap condition = JSONMap.parseJSONMap(cond.toString());

        String field = condition.getString("field");
        String keyword = condition.getString("keyword");

        if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(keyword))
        {
            switch (field)
            {
                case "equipmentId":
                    record.setEquipmentId(keyword);
                    break;
                case "equipmentName":
                    record.setEquipmentName(keyword);
                    break;
                case "type":
                    record.setType(Integer.parseInt(keyword));
                    break;
                case "station":
                    record.setStation(keyword);
                    break;
            }
        }
    }
}
